<template>
  <div class="bg-white sticky top-0 left-0 z-10">
    <ul
      ref="ulTagrget"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600"
    >
      <li
        class="absolute h-[22px] bg-zinc-900 rounded-lg duration-200 z-60"
        :style="siberStyle"
      ></li>
      <!-- 汉堡按钮 -->
      <li
        @click="handleShowPopup"
        class="
          fixed
          top-0
          right-[-1px]
          h-4
          px-1
          flex
          items-center
          bg-white
          z-20
          shadow-l-white
        "
      >
        <x-svg-icon class="w-1.5 h-1.5" name="hamburger"></x-svg-icon>
      </li>
      <li
        @click="onClickItem(index)"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
        v-for="(item, index) in $store.getters.category"
        :key="item.id"
        :ref="itemRef"
        :class="{
          'text-white': currenIndex == index,
        }"
      >
        {{ item.name }}
      </li>
    </ul>
    <x-popup v-model="isVisible">
      <MenuPage @popupClickItem="onClickItem"></MenuPage
    ></x-popup>
  </div>
</template>

<script setup>
import { ref } from "@vue/reactivity";
import { onBeforeUpdate, watch } from "@vue/runtime-core";
import { useScroll } from "@vueuse/core";
import MenuPage from "@/views/main/components/Menu/index.vue";
defineProps({});

const siberStyle = ref({
  transform: "translateX(0)",
  width: "54px",
});
const currenIndex = ref(0);
// 获取单个ref的话 dom传递的ref是字符串
const ulTagrget = ref(null);
// 监听ul滚动
const { x: ulX } = useScroll(ulTagrget);
let itemRefList = [];
// 多个dom的话 ref绑定到 是一个方法 返回所有的ref
const itemRef = (ele) => {
  if (ele) {
    itemRefList.push(ele);
  }
};

watch(
  currenIndex,
  (val) => {
    // if (itemRefList.length === 0) return;
    // 获取当前点击dom的 原生属性
    const rect = itemRefList[val].getBoundingClientRect();
    const { width, left } = rect;
    siberStyle.value = {
      transform: `translateX(${left + ulX.value - 10}px)`,
      width: `${width}px`,
    };
  }
  // 深度监听
  // { immediate: true, deep: true }
);

const onClickItem = (index) => {
  currenIndex.value = index;
  isVisible.value = false;
};
// 显示弹出层
const isVisible = ref(false);
const handleShowPopup = () => {
  isVisible.value = true;
};
onBeforeUpdate(() => {
  itemRefList = [];
});
</script>

<style>
</style>